package com.onec.service.design.proxy;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.util.HashMap;
import java.util.Map;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;


/**
 * jdk 动态代理
 */

public class DynamicPermissionProxy implements InvocationHandler {

  private static final Logger LOGGER = LoggerFactory.getLogger(DynamicPermissionProxy.class);
  // 需要代理的对象类
  private Object target;

  public DynamicPermissionProxy(Object target) {
    this.target = target;
  }


  @Override
  public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {

    LOGGER.info("切入权限验证");
    Object invoke = method.invoke(target, args);
    LOGGER.info("切入权限:记录结束");
    return invoke;
  }
}

class TestPermission {

  // 调用权限再掉日志
  public static void main(String[] args) {
    OrderServiceImpl orderServiceImpl = new OrderServiceImpl();
    Class<?> clazz = orderServiceImpl.getClass();

    DynamicLogProxy dynamicLogProxy = new DynamicLogProxy(orderServiceImpl);
    OrderService orderService = (OrderService) Proxy
        .newProxyInstance(clazz.getClassLoader(), clazz.getInterfaces(), dynamicLogProxy);

    DynamicPermissionProxy dynamicPermissionProxy = new DynamicPermissionProxy(orderService);
    OrderService orderService1 = (OrderService) Proxy
        .newProxyInstance(orderService.getClass().getClassLoader(), orderService.getClass().getInterfaces(),
            dynamicPermissionProxy);
    orderService1.createOrder();
  }

  /**
   * hashmap 动态代理 jdk 实现
   */
  public static void hashMapProxy() {
    final HashMap<String, String> proxyMap = new HashMap<>();
    Map<String, String> mapProxy = (Map<String, String>) Proxy.newProxyInstance(proxyMap.getClass().getClassLoader(),
        proxyMap.getClass().getInterfaces(),
        new InvocationHandler() {
          @Override
          public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
            return method.invoke(proxyMap, args);
          }
        });

    mapProxy.put("", "");
  }
}
